package davion.study.jwtlearn.controller;

import davion.study.jwtlearn.util.JwtUtil;
import davion.study.jwtlearn.service.UserService;
import davion.study.jwtlearn.annotation.UserLoginToken;
import davion.study.jwtlearn.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: Davion
 * @date: 2020.6.22
 * @description:
 */
@RestController
@RequestMapping("api")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/login")
    public Object login(@RequestBody User user) {
        Map<String, Object> map = new HashMap<>();
        User dbUser = userService.findByUsername(user.getUsername());
        if (dbUser == null){
            map.put("message", "登录失败，用户不存在！");
        } else {
            if (!dbUser.getPassword().equals(user.getPassword())){
                map.put("message", "登录失败，密码错误！");
            } else {
                JwtUtil jwtUtil = JwtUtil.getInstance();
                String token = jwtUtil.getToken(user);
                map.put("token", token);
                map.put("user", user);
            }
        }
        return map;
    }

    @UserLoginToken
    @GetMapping("/getMessage")
    public String getMessage(){
        return "你已通过验证";
    }
}
